package com.lagou.api;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.ACL;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

public class GetNodeData implements Watcher {

    private static ZooKeeper zooKeeper;

    /**
     * 创建会话
     *
     * @param args
     */
    public static void main(String[] args) throws IOException, InterruptedException {
        /*
             客户端可以通过创建一个zk实例来连接zk服务器
             new Zookeeper(connectString,sesssionTimeOut,Wather)
             connectString: 连接地址:IP:端口
             sesssionTimeOut:会话超时时间:单位毫秒
             Wather:监听器(当特定事件触发监听时，zk会通过watcher通知到客户端)
         */
        zooKeeper = new ZooKeeper("127.0.0.1:2181", 5000, new GetNodeData());
        //线程等待
        Thread.sleep(Integer.MAX_VALUE);
    }

    //当前类实现了Watcher接口，重写了process方法，该方法负责处理来自Zookeeper服务端的 watcher通知，
    // 在收到服务端发送过来的SyncConnected事件之后，解除主程序在CountDownLatch上 的等待阻塞，至此，会话创建完毕
    @Override
    public void process(WatchedEvent watchedEvent) {
        //⼦节点列表发⽣变化时，服务器会发出NodeChildrenChanged通知，但不会把变化情况告诉给客户端
        // 需要客户端⾃⾏获取，且通知是⼀次性的，需反复注册监听
        if (watchedEvent.getType() == Event.EventType.NodeDataChanged) {
            try {
                getChildrenData();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (KeeperException e) {
                e.printStackTrace();
            }
        }

        if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
            System.out.println("执行了process方法");
            try {
                //获取节点信息
                getNodeDataSync();
                //获取子节点信息
                getChildrenData();
                //获取acl权限信息
                getAclData();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (KeeperException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取acl权限信息
     */
    private void getAclData() throws InterruptedException, KeeperException {
        List<ACL> aclList = zooKeeper.getACL("/la_persistent", null);
        for (ACL acl : aclList) {
            System.out.println(acl);
        }
    }

    /**
     * 获取子节点信息
     */
    private void getChildrenData() throws InterruptedException, KeeperException {
        List<String> children = zooKeeper.getChildren("/la_persistent", true, null);
        for (String child : children) {
            System.out.println(child);
        }
    }

    /**
     * 获取节点信息
     */
    private void getNodeDataSync() throws InterruptedException, KeeperException {
        /**
         * path	: 获取数据的路径
         * watch	: 是否开启监听
         * stat	: 节点状态信息
         *	null: 表示获取最新版本的数据
         *	zk.getData(path, watch, stat);
         */
        byte[] data = zooKeeper.getData("/la_persistent", false, null);
        System.out.println(new String(data, StandardCharsets.UTF_8));
    }
}
